<?php
class ControllerCommonHome extends AdminController {
	public function index() {
		$this->document->setTitle($this->_['heading_title']);

		// Check install directory exists
 		if (is_dir(dirname(DIR_APPLICATION) . '/install')) {
			$this->data['error_install'] = $this->_['error_install'];
		} else {
			$this->data['error_install'] = '';
		}

		// Check image directory is writable
		$file = DIR_IMAGE . 'test';
		$handle = fopen($file, 'a+');
		fwrite($handle, '');
		fclose($handle);

		if (!file_exists($file)) {
			$this->data['error_image'] = sprintf($this->_['error_image']. DIR_IMAGE);
		} else {
			$this->data['error_image'] = '';
			unlink($file);
		}

		// Check image cache directory is writable
		$file = DIR_IMAGE . 'cache/test';
		$handle = fopen($file, 'a+');
		fwrite($handle, '');
		fclose($handle);

		if (!file_exists($file)) {
			$this->data['error_image_cache'] = sprintf($this->_['error_image_cache']. DIR_IMAGE . 'cache/');
		} else {
			$this->data['error_image_cache'] = '';
			unlink($file);
		}

		// Check cache directory is writable
		$file = DIR_CACHE . 'test';
		$handle = fopen($file, 'a+');
		fwrite($handle, '');
		fclose($handle);

		if (!file_exists($file)) {
			$this->data['error_cache'] = sprintf($this->_['error_image_cache']. DIR_CACHE);
		} else {
			$this->data['error_cache'] = '';
			unlink($file);
		}

		// Check download directory is writable
		$file = DIR_DOWNLOAD . 'test';
		$handle = fopen($file, 'a+');
		fwrite($handle, '');
		fclose($handle);

		if (!file_exists($file)) {
			$this->data['error_download'] = sprintf($this->_['error_download']. DIR_DOWNLOAD);
		} else {
			$this->data['error_download'] = '';
			unlink($file);
		}

		// Check logs directory is writable
		$file = DIR_LOGS . 'test';
		$handle = fopen($file, 'a+');
		fwrite($handle, '');
		fclose($handle);

		if (!file_exists($file)) {
			$this->data['errorlogs'] = sprintf($this->_['error_logs']. DIR_LOGS);
		} else {
			$this->data['error_logs'] = '';
			unlink($file);
		}

		$this->data['breadcrumbs'] = array();
   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->_['text_home'],
			'href'      => UA('common/home'),
      		'separator' => false
   		);

		$this->data['token'] = $this->session->data['token'];

		M('sale/order');

		$this->data['total_sale'] = $this->currency->format($this->model_sale_order->getTotalSales(), C('config_currency'));
		$this->data['total_sale_year'] = $this->currency->format($this->model_sale_order->getTotalSalesByYear(date('Y')), C('config_currency'));
		$this->data['total_order'] = $this->model_sale_order->getTotalOrders();

		M('sale/customer');

		$this->data['total_customer'] = $this->model_sale_customer->getTotalCustomers(new Query_filter(null, false));
		$this->data['total_customer_approval'] = $this->model_sale_customer->getTotalCustomersAwaitingApproval();

		M('catalog/review');

		$this->data['total_review'] = $this->model_catalog_review->getTotalReviews();
		$this->data['total_review_approval'] = $this->model_catalog_review->getTotalReviewsAwaitingApproval();

		M('sale/affiliate');

		$this->data['total_affiliate'] = $this->model_sale_affiliate->getTotalAffiliates();
		$this->data['total_affiliate_approval'] = $this->model_sale_affiliate->getTotalAffiliatesAwaitingApproval();

		//orders
		$qf = new Query_filter(null, false, 10);
		$this->data['orders'] = $this->model_sale_order->getOrders($qf);

		$order_statuses = C('cache_order_status');
		
    	foreach ($this->data['orders'] as $i => $result) {
			$this->data['orders'][$i]['total'] = $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']);
			$this->data['orders'][$i]['status'] = isset($order_statuses[$result['order_status_id']]) ? $order_statuses[$result['order_status_id']] : '';
		}

		if (C('config_currency_auto')) {
			M('localisation/currency');
			$this->model_localisation_currency->updateCurrencies();
		}

		$this->display('common/home.tpl');
  	}

	public function chart() {

		$data = array();

		$data['order'] = array();
		$data['customer'] = array();
		$data['xaxis'] = array();

		$data['order']['label'] = $this->_['text_order'];
		$data['customer']['label'] = $this->_['text_customer'];

		if (isset($this->request->get['range'])) {
			$range = $this->request->get['range'];
		} else {
			$range = 'month';
		}

		switch ($range) {
			case 'day':
				for ($i = 0; $i < 24; $i++) {
					$query = $this->db->query("SELECT COUNT(*) AS total FROM `@@order` WHERE order_status_id > " . (int)C('config_complete_status_id') . " AND (DATE(date_added) = '" . date('Y-m-d', $GLOBALS['V5_TIME']) . "' AND HOUR(date_added) = '" . (int)$i . "') GROUP BY HOUR(date_added) ORDER BY date_added ASC");

					if ($query->num_rows) {
						$data['order']['data'][]  = array($i, (int)$query->row['total']);
					} else {
						$data['order']['data'][]  = array($i, 0);
					}

					$query = $this->db->query("SELECT COUNT(*) AS total FROM  @@customer WHERE DATE(date_added) = DATE('{$GLOBALS['V5_NOW']}') AND HOUR(date_added) = '" . (int)$i . "' GROUP BY HOUR(date_added) ORDER BY date_added ASC");

					if ($query->num_rows) {
						$data['customer']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['customer']['data'][] = array($i, 0);
					}

					$data['xaxis'][] = array($i, date('H', mktime($i, 0, 0, date('n'), date('j'), date('Y'))));
				}
				break;
			case 'week':
				$date_start = strtotime('-' . date('w') . ' days');

				for ($i = 0; $i < 7; $i++) {
					$date = date('Y-m-d', $date_start + ($i * 86400));

					$query = $this->db->query("SELECT COUNT(*) AS total FROM `@@order` WHERE order_status_id > ". (int)C('config_complete_status_id') . " AND DATE(date_added) = '" . ES($date) . "' GROUP BY DATE(date_added)");

					if ($query->num_rows) {
						$data['order']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['order']['data'][] = array($i, 0);
					}

					$query = $this->db->query("SELECT COUNT(*) AS total FROM `@@customer` WHERE DATE(date_added) = '" . ES($date) . "' GROUP BY DATE(date_added)");

					if ($query->num_rows) {
						$data['customer']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['customer']['data'][] = array($i, 0);
					}

					$data['xaxis'][] = array($i, date('D', strtotime($date)));
				}

				break;
			default:
			case 'month':
				for ($i = 1; $i <= date('t'); $i++) {
					$date = date('Y') . '-' . date('m') . '-' . $i;

					$query = $this->db->query("SELECT COUNT(*) AS total FROM `@@order` WHERE order_status_id > ". (int)C('config_complete_status_id') . " AND (DATE(date_added) = '" . ES($date) . "') GROUP BY DAY(date_added)");

					if ($query->num_rows) {
						$data['order']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['order']['data'][] = array($i, 0);
					}

					$query = $this->db->query("SELECT COUNT(*) AS total FROM  @@customer WHERE DATE(date_added) = '" . ES($date) . "' GROUP BY DAY(date_added)");

					if ($query->num_rows) {
						$data['customer']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['customer']['data'][] = array($i, 0);
					}

					$data['xaxis'][] = array($i, date('j', strtotime($date)));
				}
				break;
			case 'year':
				for ($i = 1; $i <= 12; $i++) {
					$query = $this->db->query("SELECT COUNT(*) AS total FROM `@@order` WHERE order_status_id > ". (int)C('config_complete_status_id') . " AND YEAR(date_added) = '" . date('Y') . "' AND MONTH(date_added) = '" . $i . "' GROUP BY MONTH(date_added)");

					if ($query->num_rows) {
						$data['order']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['order']['data'][] = array($i, 0);
					}

					$query = $this->db->query("SELECT COUNT(*) AS total FROM  @@customer WHERE YEAR(date_added) = '" . date('Y') . "' AND MONTH(date_added) = '" . $i . "' GROUP BY MONTH(date_added)");

					if ($query->num_rows) {
						$data['customer']['data'][] = array($i, (int)$query->row['total']);
					} else {
						$data['customer']['data'][] = array($i, 0);
					}

					$data['xaxis'][] = array($i, date('M', mktime(0, 0, 0, $i, 1, date('Y'))));
				}
				break;
		}

		$this->response->setOutput(json_encode($data));
	}

	public function login() {
		$route = '';

		if (isset($this->request->get['route'])) {
			$part = explode('/', $this->request->get['route']);

			if (isset($part[0])) {
				$route .= $part[0];
			}

			if (isset($part[1])) {
				$route .= '/' . $part[1];
			}
		}

		$ignore = array(
			'common/login',
			'common/forgotten',
			'common/reset'
		);

		if (!$this->user->isLogged() && !in_array($route, $ignore)) {
			$this->redirect($this->url->link('common/login', '', 'SSL'));
		}

		if (isset($this->request->get['route'])) {
			$ignore = array(
				'common/login',
				'common/logout',
				'common/forgotten',
				'common/reset',
				'error/not_found',
				'error/permission'
			);

			$config_ignore = array();

			if (C('config_token_ignore')) {
				$config_ignore = unserialize(C('config_token_ignore'));
			}

			$ignore = array_merge($ignore, $config_ignore);

			if (!in_array($route, $ignore) && (!isset($this->request->get['token'])
					|| !isset($this->session->data['token']) || ($this->request->get['token'] != $this->session->data['token']))) {
				$this->redirect($this->url->link('common/login', '', 'SSL'));
			}
		} else {
			if (!isset($this->request->get['token']) || !isset($this->session->data['token'])
					|| ($this->request->get['token'] != $this->session->data['token'])) {
				$this->redirect($this->url->link('common/login', '', 'SSL'));
			}
		}
	}

	public function permission() {
		if (isset($this->request->get['route'])) {
			$ignore = array(
				'common/home',
				'common/login',
				'common/logout',
				'common/forgotten',
				'common/reset',
				'error/not_found',
				'error/permission'
			);
			if (!in_array(ROUTE, $ignore) && !$this->user->hasPermission('access', ROUTE)) {
				$this->redirect(UA('error/permission'));
			}
		}
	}
}
?>